<!-- /**
*@author: ptt
*@desc: 表单导出按钮
*@date: 2023/12/12
*/ -->
<template>
    <div @click="exportExel" class="ptt-btn">
        <slot>
            <span class="icon-right-export">导出 </span>
        </slot>
        <a id="downExcel" href=""> </a>
    </div>
</template>

<script>
// 工具类
import exportElTable from '../js/exportElTable.js';
export default {
    props: ['title', 'header', 'data', 'excelStyle'],
    data() {
        return {};
    },
    mounted() {},
    methods: {
        // 导出表格
        exportExel() {
            let thNames = this.header.map(item => item.prop);
            const title = this.title;
            let thead = ''; //表头结构
            this.header.forEach(item => {
                thead += `<th style=" height:50px;background-color:#f5f5f5;border:solid 1px #EBEEF5" align="center" >${item.label}</th> `;
            });
            let trStr = `<thead><tr><th style="height:60px;font-size:16px;font-weight:bold;" align="center" colspan="${thNames.length}">${title}</th></tr>
                             <tr> ${thead}  </tr></thead>`;
            const tableData = this.data;
            //循环遍历，每行加入tr标签，每个单元格加td标签
            for (let i = 0; i < tableData.length; i++) {
                trStr += `<tbody><tr>`;

                for (let j = 0; j < thNames.length; j++) {
                    const prop = thNames[j];
                    // 无数据处理
                    let value = this.$handleStr.setDefault(tableData[i][prop]);
                    // 背景色处理
                    let bgColor = '';
                    if (this.excelStyle == 'stripe') {
                        bgColor = i % 2 == 0 ? '#fff' : '#f5f5f5';
                    }
                    bgColor = tableData[i][prop + '_bgColor']
                        ? tableData[i][prop + '_bgColor']
                        : bgColor;
                    //增加\t为了不让表格显示科学计数法或者其他格式
                    if (tableData[i][prop + '_rowspan'] > 0) {
                        // 格式化单元格为文本：vnd.ms-excel.numberformat:@   格式化单元格为日期：vnd.ms-excel.numberformat:yyyy-mm-dd
                        trStr += `<td  style="vnd.ms-excel.numberformat:@;height:50px;border:1px solid #EBEEF5;background-color:${bgColor}" align="center" rowspan="${
                            tableData[i][prop + '_rowspan']
                        }">${value + '\t'}</td>`;
                    }
                }
                trStr += '</tbody></tr>';
            }
            exportElTable.exportExcel(
                trStr, // 字符串格式的表格每一行
                title, // 下载文件名
                'downExcel' //a标签的对应id
            );
        }
    }
};
</script>
<style lang="scss" scoped></style>
